﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="DST Nexdox">
//   Copyright (c) DST Nexdox. All rights reserved.
// </copyright>
// <summary>
//   Defines the Program type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace DBScripts
{
  using System;
  using System.Configuration;
  using System.Diagnostics;
  using System.Linq;
  using System.Reflection;
  using DbUp;

  public static class Program
  {
    private const Int32 ErrorExitCode = -1;

    public static Int32 Main(String[] args)
    {
      var windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
      if (windowsIdentity != null)
      {
        Console.WriteLine("User: " + windowsIdentity.Name);
      }
      else
      {
        Console.WriteLine("User Unknown");
      }

      var connectionString = args.FirstOrDefault() ?? ConfigurationManager.ConnectionStrings["BBOS"].ConnectionString;

      var upgrader =
        DeployChanges.To.SqlDatabase(connectionString)
          .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
          .LogToConsole()
          .Build();

      var result = upgrader.PerformUpgrade();

      if (!result.Successful)
      {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(result.Error);
        Console.ResetColor();

        PauseIfDevMode();

        return ErrorExitCode;
      }

      Console.ForegroundColor = ConsoleColor.Green;
      Console.WriteLine("Success!");
      Console.ResetColor();

      PauseIfDevMode();

      return 0;
    }

    private static void PauseIfDevMode()
    {
      Boolean devMode = Debugger.IsAttached;
      if (devMode)
      {
        // Prevent console from automatically closing
        Console.ReadKey();
      }
    }
  }
}
